package com.learing.note.studythread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: TODO
 * @author: 唐晓军
 * @date: 2021/10/30 11:29
 * @version: 1.0.0
 * @company: 北京凤凰学易科技有限公司
 **/
public class BuyTicket implements Runnable {
    private int ticketNums = 10;
    boolean flag = true;

    @Override
    public void run() {
        //买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void buy() throws InterruptedException {
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        //模拟延时
        //Thread.sleep(1);
        System.out.println(Thread.currentThread().getName() + "--->买到第" + ticketNums--);
    }

    public static void main(String[] args) {
        //不案例 不同人买到了同一张票
        BuyTicket buyTicket = new BuyTicket();
        Thread t1 = new Thread(buyTicket, "A");
        Thread t2 = new Thread(buyTicket, "B");
        Thread t3 = new Thread(buyTicket, "C");
        Thread t4 = new Thread(buyTicket, "D");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

class TestLock implements Runnable {
    int ticketNum = 10;
    //定义lock锁，推荐使用 try finally防止锁不释放
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (ticketNum > 0) {
                    System.out.println(ticketNum--);
                }
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        TestLock testLock = new TestLock();
        new Thread(testLock).start();
        new Thread(testLock).start();
        new Thread(testLock).start();
    }
}
